package com.oss.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Logger;

/**
 * 获取请求来源的IP地址
 */
public class IPUtils {
    static Logger log = Logger.getLogger(IPUtils.class.getName());

    private static final String[] HEADERS_TO_TRY = {
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR",
            "HTTP_X_FORWARDED",
            "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR",
            "HTTP_FORWARDED",
            "HTTP_VIA",
            "REMOTE_ADDR",
            "Request_URI",
            "X-Real-IP",
            "Host",
    };

    /**
     * 是否为无用IP
     * @param ip
     * @return
     */
    public static boolean isUselessIP(String ip){
        // 无用IP
        if (StringUtils.isNotBlank(ip) && !ip.contains("unknown") && !ip.contains("127.0.0.1") && !ip.contains("localhost") && !ip.contains("0:0:0:0:0:0:0:1")){
            return false;
        } else {
            return true;
        }
    }

    /**
     * 获取Ip地址 : 如果部署时中间有代理 , 需要配置代理 , 否则拿不到客户的IP
     * @param request HttpServletRequest 入参
     * @return ip
     */
    public static String getIpAdrress(HttpServletRequest request) {
        String rip = request.getRemoteAddr();
        try {
            String ip = InetAddress.getLocalHost().getHostAddress();
            if (isUselessIP(rip) && !isUselessIP(ip)){
                rip = ip;
            }
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
        for (String header : HEADERS_TO_TRY) {
            String ip = request.getHeader(header);
            ip = StringUtils.isNotBlank(ip) ? ip.toLowerCase() : "";
            if (isUselessIP(rip) && !isUselessIP(ip)) {
                rip = ip;
                break;
            }
        }
        int pos = rip.indexOf(',');
        if (pos >= 0) {
            rip = rip.substring(0, pos);
        }
        if (rip.indexOf(':') >= 0){
            rip = rip.substring(0, rip.indexOf(':'));
        }
        return rip;
    }
}
